package com.siyoumi.sh.modules.jm;

import com.siyoumi.sh.modules.common.IHandle;
import com.siyoumi.sh.modules.jm.entity.JmApiData;
import com.siyoumi.sh.modules.jm.entity.JmApiToken;
import com.siyoumi.sh.modules.jm.entity.StarInfo;
import com.siyoumi.sh.modules.jm.entity.StarMasterList;
import com.siyoumi.util.XApp;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class WanHandle
        extends JmHandleBase
        implements IHandle {
    @Override
    public JmApiData getJmApiData() {
        JmApiData data = new JmApiData();
        data.setApiRoot("https://s.wan.xiao-bo.com/");
        data.setSiteId("app.wan");
        data.setJmApiTokens(getArrToken());

        return data;
    }

    @Override
    public void run() {
        if (getArrToken().size() <= 0) {
            log.error("未配置WAN_TOKEN");
            return;
        }

        log.debug("WanTask_BEGIN:{}", XDate.toDateTimeString());

        Map<String, String> arrTask = getArrTask();

        StringBuilder sendMsg = new StringBuilder();
        sendMsg.append("**wan**\n\n");

        for (Map.Entry<String, String> task : arrTask.entrySet()) {
            String taskName = task.getKey();
            String returnStr = "";
            switch (taskName) {
                case "猜红包":
                    returnStr = redHandle(task);
                    break;
            }

            sendMsg.append(returnStr);
        }

        //发信息
        sendMsg(sendMsg.toString());

        log.debug("WanTask_END:{}", XDate.toDateTimeString());
    }

    public Map<String, String> getArrTask() {
        Map<String, String> arr = new HashMap<>();
        arr.put("猜红包", "sact-b83dd2d4-592f-4442-8604-551d6fd9f8e8");
        return arr;
    }

    /**
     * token格式
     * name|wx_from|wx_from_enc&name2|wx_from2|wx_from_enc2
     */
    protected List<JmApiToken> getArrToken() {
        String token = System.getenv("WAN_TOKEN");
        if (XStr.isNullOrEmpty(token)) {
            return new ArrayList<>();
        }

        List<JmApiToken> tokenArr = new ArrayList<>();
        String[] jmTokenArr = token.split("&");
        for (String s : jmTokenArr) {
            String[] dataArr = s.split("\\|");
            tokenArr.add(JmApiToken.getIns(dataArr[0], dataArr[1], dataArr[2]));
        }

        return tokenArr;
    }

    //猜红包
    protected String redHandle(Map.Entry<String, String> task) {
        StringBuilder sendMsg = new StringBuilder();
        String taskName = task.getKey();
        String actId = task.getValue(); //活动ID

        List<JmApiToken> tokenArr = getArrToken();
        //活动时间验证
        StarInfo starInfo = startInfo(actId, tokenArr.get(0));
        logAndSet(sendMsg, "**" + starInfo.getSact_name() + "** \n\n");
        logAndSet(sendMsg, "活动时间：" + XDate.toDateTimeString(starInfo.getSact_start_time())
                + "-" + XDate.toDateTimeString(starInfo.getSact_end_time())
                + " \n\n");
        XReturn rDate = starInfo.validDate();
        if (rDate.err()) {
            logAndSet(sendMsg, rDate.getErrMsg() + " \n\n");
            return sendMsg.toString();
        }

        for (JmApiToken apiToken : tokenArr) {
            logAndSet(sendMsg, "**" + apiToken.getName() + "** 开始领红包\n\n");
            int redCount = 0;
            while (true) {
                XReturn r = startLaunch(actId, apiToken);
                if (r.err()) {
                    break;
                }
                redCount++;
            }
            logAndSet(sendMsg, "当前领红包数量：" + redCount + "\n\n");

            sleepAndLog(1);
            logAndSet(sendMsg, "获取红包列表 \n\n", false);
            XReturn r = startMasterList(actId, apiToken.getWxFrom(), apiToken);
            if (r.err()) {
                logAndSet(sendMsg, "获取红包列表：" + r.getErrMsg() + "\n\n");
            } else {
                List<StarMasterList> masterList = startMasterListOfObj(r);
                logAndSet(sendMsg, "主人开始乱猜 \n\n", false);
                for (StarMasterList item : masterList) {
                    if (item.win()) continue; //猜中了
                    for (Integer i = 0; i < item.getHelpCount(); i++) {
                        int redNum = XApp.random(100, 999);
                        XReturn rHelp = startHelp(actId, item.getMasterId(), apiToken, redNum + "");
                        if (rHelp.err()) {
                        }
                        sleepAndLog(1);
                    }
                }
            }

            sleepAndLog(1);
        }

        log.debug("开始帮忙猜");
        for (JmApiToken apiTokenMaster : tokenArr) {
            for (JmApiToken apiTokenFriend : tokenArr) {
                if (apiTokenFriend.getWxFrom().equals(apiTokenMaster.getWxFrom())) {
                    logAndSet(sendMsg, "自己不帮自己猜", true);
                    continue;
                }

                sleepAndLog(2);
                List<StarMasterList> masterListByFriend = startMasterListOfObj(actId, apiTokenMaster.getWxFrom(), apiTokenFriend);
                for (StarMasterList item : masterListByFriend) {
                    if (item.win()) {
                        logAndSet(sendMsg, "已猜中", true);
                        continue;
                    }
                    if (item.getHelpCount() <= 0) {
                        logAndSet(sendMsg, "机会已用光", true);
                        continue;
                    }
                    if (XStr.toInt(item.getStr_00()) < 200) {
                        logAndSet(sendMsg, "红包小于200", true);
                        continue;
                    }

                    logAndSet(sendMsg, apiTokenFriend.getName() + " 帮 " + apiTokenMaster.getName() + " 猜[" + item.getStr_00() + "]\n\n");
                    XReturn r = startHelp(actId, item.getMasterId(), apiTokenFriend, item.getStr_00());
                    logAndSet(sendMsg, r.getErrMsg() + "\n\n");
                    if (r.err()) {
                        logAndSet(sendMsg, r.getErrMsg(), true);
                        break;
                        //if (r.getErrCode() == -70 || r.getErrCode() == -80) {
                        //}
                    }

                    item.setStr_01(XApp.getUUID()); //标记猜
                    sleepAndLog(1);
                }
            }
        }

        for (JmApiToken apiToken : tokenArr) {
            Integer fun = getFun(apiToken);

            logAndSet(sendMsg, "**" + apiToken.getName() + "** 积分：" + fun + "\n\n");
            List<StarMasterList> masterList = startMasterListOfObj(actId, apiToken.getWxFrom(), apiToken);
            for (StarMasterList item : masterList) {
                String msg = "-- 红包：" + item.getStr_00();
                if (item.win()) {
                    msg += "[猜中]";
                }
                logAndSet(sendMsg, msg + "\n\n");
            }
        }


        return sendMsg.toString();
    }


}
